package cn.nihao365.common.component;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.nihao365.common.config.AppConfig;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static cn.hutool.crypto.SecureUtil.md5;

/**
 * upload组件
 * @author zhu hui (zhuhui@nihao365.cn)
 * @version 1.0
 * @date 2021-11-09 22:28:13
 */
@Component
@Data
@Accessors(chain = true)
public class UploadComponent{
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private AppConfig appConfig;
    private List<String> limitType;
    private String path = "";
    private boolean isOriginalName = false;
    private List<Integer> imageSize;
    private String message = "";
    public static UploadComponent Util;
    protected MultipartFile file;

    @PostConstruct
    public void init(){
        Util = this;
    }

    public String upload(MultipartFile file){
        if(null == file){
            this.message = "请选择上传的文件";
            return "";
        }
        if(file.isEmpty()){
            this.message = "上传的文件内容不能为空";
            return "";
        }
        this.file = file;

        //判断文件大小
        int lSize = Integer.parseInt(appConfig.getMaxFileSize().toUpperCase().replace("MB",""))*1024*1024;
        if(lSize < this.getFileSize()){
            this.message = "文件大小不能超过"+appConfig.getMaxFileSize();
            return "";
        }

        //String mimeType = FileUtil.getMimeType(filePath);
        //System.out.println(filePath + "-->" + mimeType);
        //通过文件扩展名判断文件类型
        if(ArrayUtil.isNotEmpty(limitType) && !limitType.contains(this.getOriginalExtension())){
            this.message = "请选择["+limitType.toString()+"]类型文件";
        };

        try {
            //判断图片尺寸
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if(null != bi && ArrayUtil.isNotEmpty(imageSize) && imageSize.size() == 2){
                if(bi.getWidth() > imageSize.get(0) || bi.getHeight() > imageSize.get(1)){
                    this.message = "'图片文件尺寸必须是'"+imageSize.get(0)+'*'+imageSize.get(1);
                    return "";
                }
            }
            //保存文件
            String filePath = this.filePath()+"/"+this.getFileName();
            file.transferTo(new File(filePath));
            return filePath;
        } catch (IllegalStateException | IOException | MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            if(e instanceof MaxUploadSizeExceededException){
                this.message = "文件大小不能超过"+appConfig.getMaxFileSize();
            }
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 文件上传的路径
     * @return 文件路径
     */
    private String filePath(){
        File file = new File(servletContext.getRealPath(""));
        File upload = new File(file.getAbsolutePath()+File.separator+appConfig.getUploadLocation()+this.getPath());
        if(!FileUtil.exist(upload)){
            FileUtil.mkdir(upload);
        };
        return upload.getAbsolutePath();
    }

    /**
     * 获取文件的扩展名
     * @return 文件扩展名
     */
    private String getOriginalExtension(){
        String originalFilename = this.file.getOriginalFilename();
        String ext = "";
        if(StrUtil.contains(originalFilename,".")) {
            ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        }
        return ext.toLowerCase();
    }

    /**
     * 上传文件的原名称
     * @return 文件原名称
     */
    private String getOriginalFilename(){
        return this.file.getOriginalFilename();
    }

    /**
     * 获取文件名
     * @return 文件名
     */
    private String getFileName(){
        String fileName = this.getOriginalFilename();
        if(!this.isOriginalName){
            DateTime dateTime = new DateTime(System.currentTimeMillis());
            fileName = md5(dateTime.toString(DatePattern.NORM_DATETIME_FORMAT) + fileName)+"."+this.getOriginalExtension();
        }
        return fileName;
    }

    /**
     * 获取文件大小
     * @return 文件大小 Byte
     */
    private Integer getFileSize(){
        return  (int)this.file.getSize();
    }

    private String[] multiUpload(){
        ArrayList<String> list = new ArrayList<>();
        list.add("zhu hui111.text");
        list.add("zhu hui222.text");
        list.add("zhu hui333.text");
        return ArrayUtil.toArray(list,String.class);
    }

}
